<?php

/*

   <svn_trunk>/event_handlers/updateAnnotationCell.php

   -- Updates the Threads DB and threadJSON to reflect new thread
      information when user changes either the "Parent" or "Relation"
      column of the main jqgrid of <svn_trunk>/editAnnotation.php
   -- If the user does not actually change the contents of the cell
      (i.e., when they hit "enter" or "tab", the new value does not
       differ from the original value), the jqgrid will not call
      this script
   -- The following cases of changing a postnum's thread information
      must be handled by this module:
      1.) the postnum was previously a root, now a child
      2.) the postnum was previously a child, now a root
      3.) the postnum is now a child in a different thread
      4.) the postnum is now a child of a different postnum in the same thread

*/


require_once('../db_php/db_config.php'); // using db config variables
require_once('../db_php/Threads.php');  // using makeLispTree() and getRoot()


$filenumber = $_POST["filenumber"];
$annotator1 = $_POST["annotator1"];
$newParent = $_POST["Parent"];
$newRelation = $_POST["Relation"];
$postnum = $_POST["id"];
$threadArray = json_decode(stripslashes($_POST["threadJSON"]), true);

// Initialize response error field that ../editAnnotations.php anticipates

$response->errors = '';

// Ensure the user is still connected to the database

if(!$db)
{  $response->errors .= "Could not connect to database server. ";
   $response->threadJSON = json_encode($threadArray);
   echo json_encode($response);
   return;
}

// Ensure the user entered a valid entry into the cell

if($newParent >= $postnum)
{  $response->errors .= "Post Number $newParent is greater than or
                         equal to Post Number $postnum; therefore,
                         Post Number $newParent cannot be a parent
                         of Post Number $postnum. ";
   $response->threadJSON = json_encode($threadArray);
   echo json_encode($response);
   return;
}


// User is changing the Parent field

if(isset($newParent))
{  $rootsArray = json_decode($threadArray["roots"], true);
   $parentsArray = json_decode($threadArray["parents"], true);
   $childrenArray = json_decode($threadArray["children"], true);
   $oldthread = getRoot($parentsArray, $postnum);
   if($newParent == "-1")   $newthread = $postnum; 
   else                     $newthread = getRoot($parentsArray, $newParent);
   $oldparent = $parentsArray["$postnum"];
 
   // Check for possible data contamination.
   // This would point most probably to information in the database that
   // is incomplete (e.g., updated thread information in Annotations table,
   //                      but no associated thread tree in Threads table).

   if(is_null($oldparent))
   {  $response->errors .= "Post Number $postnum does not have a
                            parent in the Threads array. This most likely
                            points to the post not being represented in
                            any thread tree in the $threadsTable DB table. ";
      $response->threadJSON = json_encode($threadArray);
      echo json_encode($response);
      return;
   }
   
   // Case 1: $newParent is not in a thread for file $filenumber.
   //         Do not allow this case to update array or database

   if($newthread == "-1")
   {  $response->errors .= 
         "$newParent is not in a thread for file $filenumber. "; 
   }

   // Case 2: $newParent is in a thread for file $filenumber.
   //         Update both the thread array and database.
   //         The database will be attempted first, in case the updates fail.
   //         If they do fail, the array will not be updated.

   else
   {  $beginresult = @mysql_query("BEGIN;");
      $oldresult = $deloldroot = $insnewroot = true;
      $newresult1 = $newresult2 = $newresult3 = true;
      if($oldparent != "-1")
      {  array_splice($childrenArray["$oldparent"],
            array_search("$postnum", 
               $childrenArray["$oldparent"]), 1);
         if($oldthread != $newthread)
         {  $oldtree = makeLispTree($childrenArray, $oldthread);
            $oldresult = @mysql_query("UPDATE $threadsTable
                                       SET tree = '$oldtree'
                                       WHERE filenumber = $filenumber
                                       AND annotator = $annotator1
                                       AND thread = $oldthread;");
         }
      }
      else
      {  $deloldroot = @mysql_query("DELETE FROM $threadsTable
                                     WHERE filenumber = $filenumber
                                     AND annotator = $annotator1
                                     AND thread = $oldthread;");
      }
      if($newParent != "-1") 
      {  array_push($childrenArray["$newParent"], $postnum);
         sort($childrenArray["$newParent"], SORT_NUMERIC);
      }
      else
      {  $insnewroot = @mysql_query("INSERT INTO $threadsTable
                                    VALUES
                                    ($filenumber, $annotator1, $postnum, '');");
      }
      $newtree = makeLispTree($childrenArray, $newthread);
      $newresult1 = @mysql_query("UPDATE $threadsTable
                                  SET tree = '$newtree'
                                  WHERE filenumber = $filenumber
                                  AND annotator = $annotator1
                                  AND thread = $newthread;");
      
      $newresult2 = @mysql_query("UPDATE $annotationsTable
                                  SET parent = $newParent
                                  WHERE filenumber = $filenumber
                                  AND annotator = $annotator1
                                  AND postnum = $postnum;");
      if($oldthread != newthread)
      {  $possibleParents = implode(",", 
                            getNodesInThreadTree($childrenArray, $postnum));
         $possibleParents .= ", $newParent";
         $newresult3 = @mysql_query("UPDATE $annotationsTable
                                     SET thread = $newthread
                                     WHERE filenumber = $filenumber
                                     AND annotator = $annotator1
                                     AND thread = $oldthread
                                     AND postnum >= $postnum
                                     AND parent IN ($possibleParents);");
      }
      if(!($beginresult && $oldresult && $deloldroot && $insnewroot
                        && $newresult1 && $newresult2 && $newresult3))
      {  $response->errors .= mysql_error() . ". ";
         $response->errors .= "testing: " . $beginresult .
                              " " . $oldresult . " " . $deloldroot . " " .
                              $newresult1 . " " . $newresult2 . " " . 
                              $newresult3;
         $rbresult = @mysql_query("ROLLBACK;");
         if($oldparent != "-1")
         {  array_push($childrenArray["$oldparent"], $postnum);  }
         if($newParent != "-1")
         {  array_splice($childrenArray["$newParent"],
                         array_search("$postnum",
                         $childrenArray["$newParent"]), 1);
         }
      }
      else
      {  if($newParent == "-1")
         {  array_push($rootsArray, $postnum);
            sort($rootsArray, SORT_NUMERIC);
         }
         $parentsArray["$postnum"] = $newParent;
         $comresult = @mysql_query("COMMIT;");
      }
   }
   
   $threadArray["roots"] = json_encode($rootsArray);
   $threadArray["parents"] = json_encode($parentsArray);
   $threadArray["children"] = json_encode($childrenArray);
   $response->threadJSON = json_encode($threadArray);
}


// User is changing the Relation field

elseif(isset($newRelation))
{  $response->threadJSON = json_encode($threadArray);
   @mysql_query("UPDATE $annotationsTable
                 SET relation = '$newRelation'
                 WHERE filenumber = $filenumber
                 AND annotator = $annotator1
                 AND postnum = $postnum;");
}

else
{  $response->threadJSON = json_encode($threadArray);
   $response->userdata =
   array("testing" => "testing");
}

echo json_encode($response);

?>
